/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 */
import path from 'path';

import { expect } from '@jest/globals';
import fse from 'fs-extra';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType,
} from '../../plugins/project-builder/models/constants';
import { Project } from '../../plugins/project-builder/models/project-models';
import { ICaseRecord } from '../../plugins/report-builder/report-models';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption, TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.NativeC,
  },
  modulesOption: {
    [ModuleTemplateType.SharedLibraryWithC]: 1,
  },
};

const testTaskOption: TestTaskOption = TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L2).sign(SignType.NoSign).ohpmInstall(IsEnable.Enable).build();

const testFun: TestCaseFun = async (project: Project, taskConfig: TestTaskOption, record: ICaseRecord) => {
  const projectRoot = project.projectRootPath();
  // 检查编译器是不是BiSheng，在path.resolve(projectRoot, 'entry/.cxx/default/default/release/arm64-v8a/CMakeFiles/rules.ninja'
  // 看看这个文件里面的command 有没有BiSheng

  // 需要执行的命令行参数
  const commands = initExecuteCommand({
    mode: 'project',
    product: 'default',
    tasks: 'assembleApp',
    daemon: false,
  });

  // 执行编译
  const result = await runHvigorAsync(projectRoot, commands);

  // 定义文件路径
  const filePath = path.resolve(`${projectRoot}/entry/.cxx/default/default/release/arm64-v8a/CMakeFiles/rules.ninja`);
  // 读取文件内容
  const data = await new Promise<string>((resolve, reject) => {
    fse.readFile(filePath, 'utf8', (err, data) => {
      resolve(data);
    });
  });

  // 正则表达式匹配规则
  const rulePattern = /rule\s+CXX_COMPILER__entry_unscanned_Release([\s\S]*?)description\s*=\s*Building CXX object/;
  const match = data.match(rulePattern);

  // 断言：如果匹配到规则，检查是否包含 "BiSheng"
  expect(match).not.toBeNull(); // 断言找到了规则

  // @ts-ignore
  const ruleContent = match[1];

  // 记录测试日志
  record.addStep('Build App', result);
  expect(ruleContent).toContain('BiSheng');
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
};

// 需求回退了,E2E先不执行
/*
TestCaseBuilder.builder()
  .caseName('AR20241111665217')
  // eslint-disable-next-line max-len
  .description('切换默认编译器为毕昇')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(testTaskOption)
  .testFun(testFun)
  .load();
 */
